/**
 *******************************************************************************
 *  @copyright Copyright (c) 2022  <dx_65535@163.com>. 
 * 
 *  @file demo_uart_test.cc
 *  @author Xiang.D (dx_65535@163.com)
 *  @version 1.0
 *  @brief Blog: https://linuxtaoist.gitee.io
 *  @date 2022-06-20
 * 
 * 
 *  Change History:
 *  <Date>     | <Version> | <Author>       | <Description>
 *------------------------------------------------------------------------------
 *  2022/06/20 | 1.0.0.1   | Xiang.D        | Create file
 *------------------------------------------------------------------------------
 * 
 *******************************************************************************
 */

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <fcntl.h>
#include "common_type.h"
#include "event_handler.h"

#define LOGD(fmt, args...) printf("%d DemoMq D: " fmt, __LINE__, ##args)
#define LOGE(fmt, args...) printf("%d DemoMq E: " fmt, __LINE__, ##args)

const char DEVICE_NAME[] = "/DemoQueue";

int main(int argc, char *argv[])
{
    ssize_t ret;
    mq_attr mqAttr;
    mqAttr.mq_maxmsg = 10;      // cat /proc/sys/fs/mqueue/msg_max
    mqAttr.mq_msgsize = 1025;

    mq_unlink(DEVICE_NAME);
    mqd_t fd = mq_open(DEVICE_NAME, O_RDWR | O_CREAT | O_EXCL, 0666, &mqAttr);
    if(fd < 0) {
        LOGE("Open %s failed. (%s)\n", DEVICE_NAME, strerror(errno));
        return -1;
    }

    CEventHandler theEventHandler;
    theEventHandler.Init();

    theEventHandler.RegisterEvent(fd, CHANNEL_MQ, NULL);

    theEventHandler.Run();

    SCmdFrame dataFrame = { CHANNEL_MQ, CMD_LED_OFF, strlen("led off"), "led off" };
    ret = mq_send(fd, (const char*)&dataFrame, sizeof(SCmdFrame), 1);
    if (ret < 0) {
        LOGE("write failed! (%s)\n", strerror(errno));
    } else {
        LOGD("write success.\n");
    }

    while(1);
    theEventHandler.Exit();
    close(fd);

    return 0;
}

